#!/usr/bin/perl
# 2012/11/27 Remove low quality mapping reads (it also remove repeat reads since those have 0 qulaity value)

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;


if(@ARGV != 4 or $ARGV[0] eq '--help'){
	die "Usage : $0 -i [map file] -o [output filtered map file]\n";
}

#---------------------------------------
# map format
#---------------------------------------
# id chr1 loc1 direction1 quality1 hind1 hind_loc1 chr2 loc2 direction2 quality2 hind2 hind_loc2 type(unique or repeat) number(alignable locations) locations

my %opt;
getopts("i:o:", \%opt);
my $FILE_map = $opt{i};
my $FILE_out = $opt{o};

my $COUNTER_all = 0;
my $COUNTER_goodQuality = 0;


my $fh_out = IO::File->new($FILE_out, 'w') or die "cannot write $FILE_out: $!";
my $fh_map = IO::File->new($FILE_map) or die "cannot open $FILE_map: $!";
while($_ = $fh_map->getline()){
	s/\r?\n//;
	my ($id, $chr1, $loc1, $direction1, $mapQ1, $hinID1, $hinLoc1, $chr2, $loc2, $direction2, $mapQ2, $hinID2, $hinLoc2, $type, $num, $locations) = split /\t/;
	if($mapQ1 > 19 and $mapQ2 > 19){
		$fh_out->print("$_\n");
		$COUNTER_goodQuality++;
	}
	$COUNTER_all++;
}
$fh_map->close();
$fh_out->close();

print "Removed low quality (MapScore is less than 20) \n";
printf "Total reads: %d\n", $COUNTER_all;
printf "After filtering reads: : %d (%.3f)\n\n", $COUNTER_goodQuality, $COUNTER_goodQuality/ $COUNTER_all * 100;
